<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>钢琴</title>
    <style>
    html{
        width: 100%;
        height: 100%;
    }
    body{
        width: 100%;
        height: 100%;
        margin: 0;
        background: radial-gradient(#aaa,#666,#000);
        /* 弹性布局,居中 */
        display: flex;
        justify-content: center;
        align-items: center;
    }
    main{
        width: 100%;
        height: 100%;
        background-image: url(keys.png);
        /* 最大宽高 */
        max-width: 800px;
        max-height: 400px;
        background-size: 100% 100%;
        border: solid 20px pink;
        border-top-width: 40px;
        /* 边框向内压缩 */
        box-sizing: border-box;
        /* 边框阴影 */
        box-shadow: 0px 0px 20px #aaa;
        display: flex;
    }
    div{
        flex-grow: 1;
    }
    div:active,div.press{
        background-image: linear-gradient(rgba(255,255,255,0),rgba(255,255,255,0),rgba(150,150,150,1));
    }
    </style>
</head>
<body>
    <audio src="notes/1.oga"></audio>
    <audio src="notes/2.oga"></audio>
    <audio src="notes/3.oga"></audio>
    <audio src="notes/4.oga"></audio>
    <audio src="notes/5.oga"></audio>
    <audio src="notes/6.oga"></audio>
    <audio src="notes/7.oga"></audio>
    <audio src="notes/8.oga"></audio>
    <audio src="notes/9.oga"></audio>
    <main>
        <div onmousedown="play(0)"></div>
        <div onmousedown="play(1)"></div>
        <div onmousedown="play(2)"></div>
        <div onmousedown="play(3)"></div>
        <div onmousedown="play(4)"></div>
        <div onmousedown="play(5)"></div>
        <div onmousedown="play(6)"></div>
        <div onmousedown="play(7)"></div>
        <div onmousedown="play(8)"></div>
        
    </main>
</body>
</html>
<script>
    //找到所有的音频播放标签
    var audios = document.getElementsByTagName("audio");
    //找到所有的div标签
    var divs = document.getElementsByTagName("div");
    //播放声音的函数
    function play(index){
        var au = audios[index];
        au.load();
        au.play();
    }
    var code = 0;
    //点击数字1-9
    window.onkeydown = function name(e) {
        // console.log("我按下了键盘");
        //1-9 ASCII:49-57
        if (code == e.keyCode) return;


        code = e.keyCode
        if (code >=49 && code<=57) {
            play(code-49);
            //给按下键盘对应的div添加class
            divs[code-49].classList.add("press");
        }
    }
    window.onkeyup = function name(params) {
        code = 0;
        //给div移除press这个class
        for(var i = 0;i < divs.length;i++){
            divs[i].classList.remove("press");
        }
    }
</script>